<template>
  <div class="navbar">
    <div class="left-side">
      <a-space>
        <img alt="logo" :src="logo" style="width: 180px" />
        <!-- <a-typography-title
          :style="{ margin: 0, fontSize: '18px' }"
          :heading="5"
        >
          Mes 3.0
        </a-typography-title> -->
        <icon-menu-fold
          v-if="appStore.device === 'mobile'"
          style="font-size: 22px; cursor: pointer"
          @click="toggleDrawerMenu"
        />
      </a-space>
    </div>

    <div class="menu-demo">
      <a-menu
        mode="horizontal"
        :default-selected-keys="[defaultCurrMenusKey]"
        :selected-keys="[currMenusKey]"
        @menu-item-click="itemClick($event, 'Click')"
      >
        <a-menu-item
          ref="menusRef"
          class="menu-item"
          v-for="item in menus"
          :key="item.key"
        >
          <span style="font-size: 16px; font-weight: bold">
            {{ item.name }}
          </span>
          <template #icon>
            <i :class="getIcon(item.icon)"></i>
            <!-- <img class="header-icon" :src="item.isActive ? item.icon_active : item.icon" alt="" /> -->
            <!-- <component :is="item.icon"></component> -->
          </template>
        </a-menu-item>
      </a-menu>
    </div>

    <ul class="right-side">
      <!-- <li>
        <a-tooltip :content="'settings.search'">
          <a-button class="nav-btn" type="outline" :shape="'circle'">
            <template #icon>
              <icon-search />
            </template>
          </a-button>
        </a-tooltip>
      </li> -->
      <!-- <li>
        <a-tooltip :content="'settings.navbar.alerts'">
          <div class="message-box-trigger">
            <a-badge :count="9" dot>
              <a-button
                class="nav-btn"
                type="outline"
                :shape="'circle'"
                @click="setPopoverVisible"
              >
                <icon-notification />
              </a-button>
            </a-badge>
          </div>
        </a-tooltip>
        <a-popover
          trigger="click"
          :arrow-style="{ display: 'none' }"
          :content-style="{ padding: 0, minWidth: '400px' }"
          content-class="message-popover"
        >
          <div ref="refBtn" class="ref-btn"></div>
          <template #content>
            <message-box />
          </template>
        </a-popover>
      </li> -->
      <li>
        <a-tooltip :content="'settings.title'">
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="setVisible"
          >
            <template #icon>
              <icon-settings />
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li>
        <a-dropdown trigger="click">
          <a-avatar
            :size="32"
            :style="{ marginRight: '8px', cursor: 'pointer' }"
          >
          </a-avatar>
          <template #content>
            <a-doption>
              <a-space direction="vertical" fill>
                <a-space @click="handleLogout">
                  <icon-export />
                  <span>
                    {{ '退出登录' }}
                  </span>
                </a-space>
              </a-space>
            </a-doption>
          </template>
        </a-dropdown>
      </li>
    </ul>
  </div>
</template>

<script lang="ts" setup>
  import { useRouter, useRoute } from 'vue-router';
  import { computed, ref, inject, reactive, nextTick, watchEffect } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { useDark, useToggle, useFullscreen } from '@vueuse/core';
  import {
    useAppStore,
    useUserStore,
    useMenusStore,
    useRouterStore,
  } from '@/store';
  // import { LOCALE_OPTIONS } from '@/locale';
  import usePermission from '@/hooks/permission';
  // import useLocale from '@/hooks/locale';
  import useUser from '@/hooks/user';
  import MessageBox from '../message-box/index.vue';
  import { NavbarMenus } from './type';
  import logo from '../../assets/images/logo.png';

  // request('../../assets/images/logo.png');

  const routerStore = useRouterStore();
  const router = useRouter();
  const route = useRoute();
  const appStore = useAppStore();
  const userStore = useUserStore();
  const menusStore = useMenusStore();
  const { logout } = useUser();
  // const { changeLocale } = useLocale();
  const { isFullscreen, toggle: toggleFullScreen } = useFullscreen();
  // const locales = [...LOCALE_OPTIONS];
  const avatar = computed(() => {
    return userStore.avatar;
  });

  const userInfo = JSON.parse(sessionStorage.getItem('loginInfo') as any);

  // // 记录当前头部菜单的key
  // let currMenusKey = ref(
  //   sessionStorage.getItem('SideBarRouters')
  //     ? JSON.parse(sessionStorage.getItem('SideBarRouters') as any).meta.key
  //     : menusStore.currMenus[0].meta?.key
  // );
  const getIcon = (icon: string) => {
    return `iconfont ${icon}`;
  };
  const defaultCurrMenusKey = ref('/homepage');
  const currMenusKey = ref();
  const menuItem = reactive<NavbarMenus[]>([
    {
      name: '首页',
      key: '/homepage',
      icon: 'icon-shouye',
      path: '/homepage',
      show: false,
    },
    {
      name: '销售管理',
      key: '/order',
      icon: 'icon-xiaoshouguanlifenxi',
      path: '/order',
      show: false,
    },
    {
      name: '库存管理',
      key: '/inventory',
      icon: 'icon-cangkuguanli',
      path: '/inventory',
      show: false,
    },
    {
      name: '采购管理',
      key: '/buyMg',
      icon: 'icon-caigouguanli_icox',
      path: '/buyMg',
      show: false,
    },
    {
      name: '生产管理',
      key: '/production',
      icon: 'icon-shengchanshebei',
      path: '/production',
      show: false,
    },
    {
      name: '合同管理',
      key: '/contract',
      icon: 'icon-hetongguanli1',
      path: '/contract',
      show: false,
    },
    {
      name: '设备管理',
      key: '/equipment',
      icon: 'icon-shebeiweihu',
      path: '/equipment',
      show: false,
    },
    {
      name: '工厂建模',
      key: '/FactoryModeling',
      icon: 'icon-chanpinjianmo',
      path: '/FactoryModeling',
      show: false,
    },
  ]);

  const getMenu = () => {
    const arr = JSON.parse(sessionStorage.getItem('SideBarRouters') as any);
    menuItem.forEach((item) => {
      arr?.forEach((ele) => {
        if (ele.meta.locale === item.name) {
          item.show = true;
        }
      });
    });
  };
  getMenu();

  const menus = computed(() => {
    const newArr = [];
    menuItem.forEach((item: any) => {
      if (item.show === true) {
        newArr.push(item);
      }
    });
    return newArr;
  });

  let currPath = ref(); // 获取当前menus的path，根据path在pinia里面进行侧边路由菜单的获取

  // const getItem = () => {
  //   routerStore.routes.forEach((item: any, index) => {
  //     menus.push({
  //       name: item.meta?.locale,
  //       key: item.path,
  //       icon: 'icon-settings',
  //       path: item.path,
  //     });
  //     // currPath
  //   });
  // };
  // getItem();
  const SwitchType = ref();
  const CurrentRoute = ref();
  const CurrentQuery = ref();

  // 点击头部导航菜单，获取对应的侧边栏菜单
  const itemClick = (key: string, type?: string) => {
    menus.value.forEach((item) => {
      if (item.key === key) currPath.value = item.path;
    });
    currMenusKey.value = currPath.value;
    SwitchType.value = type;

    // 根据key来判断，点击头部导航栏默认跳到第一个菜单
    switch (currPath.value) {
      case '/homepage':
        if (SwitchType.value !== 'Click') {
          router.push({
            path: CurrentRoute.value,
            query: CurrentQuery.value,
          });
        } else if (SwitchType.value === 'Click') {
          router.push({
            path: '/homepage/Workplace',
          });
        }
        break;
      case '/order':
        if (SwitchType.value !== 'Click') {
          router.push({
            path: CurrentRoute.value,
            query: CurrentQuery.value,
          });
        } else {
          router.push({
            path: '/order/base-setting',
          });
        }
        break;
      case '/buyMg':
        if (SwitchType.value !== 'Click') {
          router.push({
            path: CurrentRoute.value,
            query: CurrentQuery.value,
          });
        } else {
          router.push({
            path: '/buyMg/BuyMgBaseSetting',
          });
        }
        break;
      case '/inventory':
        if (SwitchType.value !== 'Click') {
          router.push({
            path: CurrentRoute.value,
            query: CurrentQuery.value,
          });
        } else {
          router.push({
            path: '/inventory/InventorySetting',
          });
        }
        break;
      case '/contract':
        if (SwitchType.value !== 'Click') {
          router.push({
            path: CurrentRoute.value,
            query: CurrentQuery.value,
          });
        } else {
          router.push({
            path: '/contract/ContractSetting',
          });
        }
        break;
      case '/equipment':
        if (SwitchType.value !== 'Click') {
          router.push({
            path: CurrentRoute.value,
            query: CurrentQuery.value,
          });
        } else {
          router.push({
            path: '/equipment/EquipmentBaseSetting',
          });
        }
        break;
      case '/FactoryModeling':
        if (SwitchType.value !== 'Click') {
          router.push({
            path: CurrentRoute.value,
            query: CurrentQuery.value,
          });
        } else {
          router.push({
            path: '/FactoryModeling/FactoryBaseSetting',
          });
        }
        break;
      case '/production':
        if (SwitchType.value !== 'Click') {
          router.push({
            path: CurrentRoute.value,
            query: CurrentQuery.value,
          });
        } else {
          router.push({
            path: '/production/ProductionBaseSetting',
          });
        }
        break;
      default:
        break;
    }
    menusStore.setCurrMenus(currPath.value);
  };

  watchEffect(() => {
    CurrentRoute.value = route.matched[1].path;
    CurrentQuery.value = route.query;
    if (SwitchType.value !== 'Click' && SwitchType.value === undefined) {
      itemClick(route.matched[0].path);
    } else {
      SwitchType.value = undefined;
    }
  });

  const theme = computed(() => {
    return appStore.theme;
  });
  const isDark = useDark({
    selector: 'body',
    attribute: 'arco-theme',
    valueDark: 'dark',
    valueLight: 'light',
    storageKey: 'arco-theme',
    onChanged(dark: boolean) {
      // overridden default behavior
      appStore.toggleTheme(dark);
    },
  });
  const toggleTheme = useToggle(isDark);
  const handleToggleTheme = () => {
    toggleTheme();
  };
  const setVisible = () => {
    appStore.updateSettings({ globalSettings: true });
  };
  const refBtn = ref();
  const triggerBtn = ref();
  const setPopoverVisible = () => {
    const event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    refBtn.value.dispatchEvent(event);
  };
  const handleLogout = () => {
    logout();
  };
  const setDropDownVisible = () => {
    const event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    triggerBtn.value.dispatchEvent(event);
  };
  const switchRoles = async () => {
    const res = await userStore.switchRoles();
    Message.success(res as string);
  };
  const toggleDrawerMenu = inject('toggleDrawerMenu') as () => void;
</script>

<style scoped lang="less">
  .navbar {
    display: flex;
    justify-content: space-between;
    height: 100%;
    background-color: var(--color-bg-2);
    border-bottom: 1px solid var(--color-border);
  }

  .arco-icon {
    font-size: 20;
  }

  .left-side {
    display: flex;
    align-items: center;
    padding-left: 20px;
  }

  .menu-demo {
    // box-sizing: border-box;
    width: 100%;
    // padding: 40px;
    // display: flex;
    text-align: center;
  }

  .right-side {
    display: flex;
    padding-right: 20px;
    list-style: none;

    :deep(.locale-select) {
      border-radius: 20px;
    }

    li {
      display: flex;
      align-items: center;
      padding: 0 10px;
    }

    a {
      color: var(--color-text-1);
      text-decoration: none;
    }

    .nav-btn {
      border-color: rgb(var(--gray-2));
      color: rgb(var(--gray-8));
      font-size: 16px;
    }

    .trigger-btn,
    .ref-btn {
      position: absolute;
      bottom: 14px;
    }

    .trigger-btn {
      margin-left: 14px;
    }
  }
</style>

<style lang="less">
  .message-popover {
    .arco-popover-content {
      margin-top: 0;
    }
  }
</style>
